rm(list=ls())
setwd('~/Dropbox/Farm Subsidies and Committees/analyses/summary/')

library(dplyr)
library(magrittr)
library(stringr)
library(haven)

library(xtable)
options(xtable.floating = FALSE)
options(xtable.timestamp = "")


sudta = read_dta('summary_noorgs.dta')

# function for computing column
get_col = function(df) {
    df %<>% na.omit
    out_df = data.frame(voted = mean(df$voted) * 100,
                        ran = mean(df$ran) * 100,
                        won = mean(df$winner) * 100,
                        # served = mean(df$served) * 100,
                        avg_pay_pos = mean(as.numeric(df$amt_all > 0)) * 100,
                        avg_pay = mean(df$amt_all),
                        avg_pay_ln = log(mean(df$amt_all)),
                        nobs = nrow(df))
    
    return(out_df)
}


# construct table
table_df = sudta %>% filter(election_year_desc == 2009) %>% get_col()

for (y in 2010:2015) {
    tmp_sudta = sudta %>% filter(election_year_desc == y)
    table_df %<>% bind_rows(get_col(tmp_sudta))
}

# format table
transposed = t(table_df)

transposed = rbind(transposed[1:(nrow(transposed) - 1),], 
                   rep(NA, ncol(transposed)), 
                   transposed[nrow(transposed),])

# colnames(transposed) = c('All', 'Whites', 'Non-whites', 'Blacks', 'Asians', 'Non-white hispanics', 'Others')
colnames(transposed) = 2009:2015


rownames(transposed) = c('Voted in election (%)',
                         'Ran for office (%)',
                         'Won election (%)',
                         # 'Won election cond. on running (%)',
                         #'Served on committee (%)',
                         'Share received payment (%)',
                         'Avg. yearly payment ($)',
                         'Log avg. yearly payment($)',
                         '',
                         'Number of farmer IDs')
                         # 'N (2009 - 2015)')

formatted_table = xtable(transposed, caption = 'Descriptive statistics')
digits(formatted_table) = rbind(matrix(2, nrow = nrow(transposed) - 1, ncol = ncol(transposed) + 1), matrix(0, nrow = 1, ncol = ncol(transposed) + 1))
align(formatted_table) = c('l', rep('c', ncol(transposed)))

print(formatted_table, 
      type = 'latex', 
      file = 'summary_allyrs.tex',
      caption.placement = 'top',
      floating = TRUE,
      booktabs = TRUE)
